package com.liumin.demo.comlink.base;

import com.liumin.comlink.http.exception.ApiException;
import com.liumin.comlink.http.exception.ExceptionHandle;

import org.reactivestreams.Publisher;

import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.functions.Function;

/**
 * 描述：flowable 异常处理，系统网络异常和自定义异常
 * 时间：2024/11/4 10:30
 * 作者:  Liumin
 */
public class ErrorHandlerFlowable {


    public static <T> FlowableTransformer<T, T> handleResult() {
        return upstream ->
                upstream.onErrorResumeNext(new ErrorResumeFunction<>())
                        .flatMap(new ResponseFunction<>());
    }

    /**
     * 非服务器产生的异常，比如本地无无网络请求，Json数据解析错误等等。
     *
     * @param <T>
     */
    private static class ErrorResumeFunction<T> implements Function<Throwable, Publisher<? extends T>> {

        @Override
        public Flowable<? extends T> apply(Throwable throwable) throws Exception {
            throwable.printStackTrace();
            return Flowable.error(ExceptionHandle.handleException(throwable));
        }
    }

    private static class ResponseFunction<T> implements Function<T, Publisher<T>> {

        @Override
        public Flowable<T> apply(T tResponse) throws Exception {
            BaseResponse baseResponse = (BaseResponse) tResponse;
            int code = Integer.parseInt(baseResponse.getCode());
            String message = baseResponse.getMsg();
            if (200 == code) {
                return Flowable.just(tResponse);
//                return null;
            } else {
                return Flowable.error(new ApiException(code, message));
            }
        }
    }

    public static <T> FlowableTransformer<BaseResponse<T>, T> handleResponse() {   //compose判断结果
        return (httpResponseFlowable) -> httpResponseFlowable.flatMap(new Function<BaseResponse<T>, Publisher<? extends T>>() {
            @Override
            public Publisher<T> apply(BaseResponse<T> t) throws Exception {
                int code = Integer.parseInt(t.getCode());
//                if (200 == code) {
//                    return Flowable.just(t.getRows());
//                } else {
//                    return Flowable.error(new Throwable(t.getMsg()));
//                }
                return null;
            }
        });
    }
}
